package com.android.gufengmall.my;

import android.os.Bundle;

import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.gufengmall.App;
import com.android.gufengmall.BaseActivity;
import com.android.gufengmall.R;
import com.android.gufengmall.adapter.AddressAdapter;
import com.android.gufengmall.adapter.OrderAdapter;
import com.android.gufengmall.bean.AddressBean;
import com.android.gufengmall.bean.OrderBean;
import com.android.gufengmall.gen.DaoSession;
import com.android.gufengmall.gen.OrderBeanDao;

import java.util.ArrayList;
import java.util.List;

public class OrderActivity extends BaseActivity implements OrderAdapter.IDeleteLongClick{

    private RecyclerView mRvOrder;
    private OrderAdapter mOrderAdapter;
    private List<OrderBean> mOrderBeanList;

    private App mMyApp;
    private DaoSession mDaoSession;
    private OrderBeanDao mOrderBeanDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order);

        initView();
        initData();
        initListener();
    }

    private void initListener() {
        findViewById(R.id.img_back).setOnClickListener(v -> {
            finish();
        });
    }

    private void initData() {
        mOrderBeanList = new ArrayList<>();

        mMyApp = (App) this.getApplication();
        mDaoSession = mMyApp.getDaoSession();
        mOrderBeanDao = mDaoSession.getOrderBeanDao();

        List<OrderBean> orderBeans = mOrderBeanDao.loadAll();
        mOrderBeanList.addAll(orderBeans);

        mRvOrder.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mOrderAdapter = new OrderAdapter(this, mOrderBeanList);
        mOrderAdapter.setIDeleteLongClick(this);
        mRvOrder.setAdapter(mOrderAdapter);
    }

    private void initView() {
        mRvOrder = findViewById(R.id.rv_order);
    }

    @Override
    public void onLongClickDelete(int position) {
        AlertDialog.Builder inputDialog =
                new AlertDialog.Builder(OrderActivity.this);
        inputDialog.setTitle("提示");
        inputDialog.setMessage("确认删除该订单吗？");
        inputDialog.setPositiveButton("确认", (dialog, which) -> {
            OrderBean orderBean = mOrderBeanList.get(position);
            mOrderBeanDao.delete(orderBean);
            mOrderBeanList.remove(position);
            mOrderAdapter.notifyDataSetChanged();
            showToast("删除成功");
            dialog.dismiss();
        });
        inputDialog.setNegativeButton("取消",null);
        inputDialog.show();
    }
}